//
//  YWSelectContactTableViewController.m
//  maintain
//
//  Created by Kyo on 16/8/29.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWSelectContactTableViewController.h"
#import "UIColor+CustomColors.h"
#import "YWCommonTool.h"

#import "PinYin4Objc.h"
#import "pinyin.h"
#import "YWLoginUser.h"
#import "YWLoginTool.h"

#import "YWDepartment.h"
#import "YWHandler.h"
#import "YWContactManager.h"
#import "YWContactHeadFooterView.h"
#import "YWSelectContanctCell.h"

#define KHeadViewBaseTag 300
@interface YWSelectContactTableViewController ()<YWContactHeadFooterViewDelegate,UISearchResultsUpdating,UISearchControllerDelegate>{
    NSIndexPath *lastIndexPath;
}
//部门数组
@property (nonatomic, strong) NSMutableArray *groupArray;
//所有联系人
@property (nonatomic, strong) NSMutableArray *allContacts;
//搜索的结果数据
@property (nonatomic, strong) NSMutableArray  *searchList;
//搜索的控制器
@property (nonatomic, strong) UISearchController *searchController;
//多选的数据数组
@property (nonatomic, strong) NSMutableArray *selectedContactArray;
@end

@implementation YWSelectContactTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = self.titleName?:NSLocalizedString(@"selectContact", nil);
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self initTableView];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"finish", nil) style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemEvent:)];
}

- (void)setAllJoinUser:(NSArray *)allJoinUser{
    _allJoinUser = allJoinUser;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"cancel", nil) style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItemEvent:)];
}

- (void)initTableView{
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.rowHeight = 60.0f;
    self.tableView.tableFooterView = [[UIView alloc]init];
    
    _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    _searchController.searchResultsUpdater = self;
    _searchController.delegate = self;
    _searchController.dimsBackgroundDuringPresentation = NO;
    [_searchController.searchBar sizeToFit];
    
    UIColor *color =  [UIColor colorWithRed:222/255.0 green:222/255.0 blue:222/255.0 alpha:1.0];
    _searchController.searchBar.layer.borderWidth = 1;
    _searchController.searchBar.layer.borderColor = [color CGColor];
    _searchController.searchBar.barTintColor = color;
    [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitle:NSLocalizedString(@"sure", nil)];
    self.tableView.tableHeaderView = _searchController.searchBar;
    [self.tableView setEditing:YES];
}

- (NSMutableArray *)groupArray{
    if (!_groupArray) {
        _allContacts = [NSMutableArray array];
        NSArray *alldepartment = nil;
        if (self.buildingId.length) {
            alldepartment = [[YWContactManager shareManager] departmentWithHandlersByBuildingId:self.buildingId];
        }else{
            YWLoginUser *currentUser = [YWLoginTool loginUser];
            alldepartment = [[YWContactManager shareManager] departmentWithHandlersByOrganizationNo:currentUser.companyAccount];
        }
        [alldepartment enumerateObjectsUsingBlock:^(YWDepartment*  _Nonnull department, NSUInteger idx, BOOL * _Nonnull stop) {
            [department.memberArray enumerateObjectsUsingBlock:^(YWHandler*  _Nonnull handler, NSUInteger idx, BOOL * _Nonnull stop) {
                handler.pinYin = [self nameToPinYinWith:handler.userName?:@""];
                handler.firstLetter = [self namToPinYinFisrtNameWith:handler.userName?:@""];
                handler.departmentId = department.departmentId;
                if (self.isMultiSelect) {
                    [self setupMultipleContactArray:handler department:department];
                }
            }];
            department.memberArray = [self sortWithContacts:department.memberArray];
            [_allContacts addObjectsFromArray:department.memberArray];
        }];
        _groupArray = [NSMutableArray arrayWithArray:alldepartment];
        if (_allContacts.count) {
            
        }
    }
    return _groupArray;
}

- (NSArray *)sortWithContacts:(NSArray*)contacts{
    NSSortDescriptor *firstDescriptor = [[NSSortDescriptor alloc] initWithKey:@"pinYin" ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObjects:firstDescriptor, nil];
    NSArray *sortedArray = [contacts sortedArrayUsingDescriptors:sortDescriptors];
    return sortedArray;
}

- (void)setupMultipleContactArray:(YWHandler*)handler department:(YWDepartment*)department{
    NSInteger uniqueId = handler.uniqueId;
    NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"uniqueId", uniqueId];
    
    //NSMutableArray *searchResults = [_ownContacts mutableCopy];
    NSArray *array = [[self.ownContacts filteredArrayUsingPredicate:searchPredicate] mutableCopy];
    if (array.count>0 && handler) {
        //这里再次去过滤是防止一个人在多个机构，选人的时候会有两个一样的人
        NSArray *array = [[self.selectedContactArray filteredArrayUsingPredicate:searchPredicate] mutableCopy];
        if (array.count == 0) {
            [self.selectedContactArray addObject:handler];
            department.isOpen = YES;
        }
    }
}

- (void)setOwnContacts:(NSArray *)ownContacts{
    _ownContacts = ownContacts;
}

- (NSMutableArray *)selectedContactArray{
    if (!_selectedContactArray) {
        _selectedContactArray = [NSMutableArray array];
    }
    return _selectedContactArray;
}

#pragma mark - dataSource and delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_searchController.active) {
        return 1;
    }else{
        return self.groupArray.count;
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_searchController.active) {
        return [self.searchList count];
    }else{
        YWDepartment *department = self.groupArray[section];
        NSInteger count = department.isOpen ? department.memberArray.count : 0;
        return count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YWSelectContanctCell *cell = [YWSelectContanctCell cellWithTableView:tableView];
    YWHandler *contact = nil;
    if (_searchController.active) {
        contact = self.searchList[indexPath.row];
    }else{
        YWDepartment *department = self.groupArray[indexPath.section];
        contact = department.memberArray[indexPath.row];
    }
    cell.contact = contact;
    return cell;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_searchController.active) {
        YWHandler *contact = self.searchList[indexPath.row];
        if ([self.selectedContactArray containsObject:contact]) {
            [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
        }else{
            [tableView deselectRowAtIndexPath:indexPath animated:NO];
        }
    }else{
        YWDepartment *department = self.groupArray[indexPath.section];
        YWHandler *contact = department.memberArray[indexPath.row];
        if ([self.selectedContactArray containsObject:contact]) {
            [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
            lastIndexPath = indexPath;
        }else{
            [tableView deselectRowAtIndexPath:indexPath animated:NO];
        }
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (_searchController.active) {
        return nil;
    }else{
        YWContactHeadFooterView *headView = [YWContactHeadFooterView headerWithTableView:tableView];
        
        headView.delegate = self;
        headView.showOrganizationName = self.buildingId.length >0 ? YES : NO;
        headView.department = self.groupArray[section];
        headView.tag = KHeadViewBaseTag + section;
        return headView;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (_searchController.active) {
        return 0.0f;
    }else{
        return 40.0f;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    YWHandler *contact = nil;
    if (_searchController.active) {
        contact = self.searchList[indexPath.row];
        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"departmentId", contact.departmentId];
        NSArray *array = [[self.groupArray filteredArrayUsingPredicate:searchPredicate] mutableCopy];
        if (array.count==1) {
            YWDepartment *department = array[0];
            department.isOpen = YES;
        }
    }else{
        YWDepartment *department = self.groupArray[indexPath.section];
        contact = department.memberArray[indexPath.row];
    }
    
    BOOL contain = NO;
    if (_allJoinUser.count>0) {
        NSInteger uniqueId = contact.uniqueId;
        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"uniqueId", uniqueId];
        NSArray *array = [[_allJoinUser filteredArrayUsingPredicate:searchPredicate] mutableCopy];
        if (array.count>0 && contact) {
            contain = YES;
        }
    }
    if (contain) {
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"thisUserIsAlreadyObserver", nil)];
    }else{
        if (self.isMultiSelect) {
            //多选
            if (![self.selectedContactArray containsObject:contact]) {
                //这里再次去过滤是防止一个人在多个机构，选人的时候会有两个一样的人
                NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"uniqueId", contact.uniqueId];
                NSArray *array = [[self.selectedContactArray filteredArrayUsingPredicate:searchPredicate] mutableCopy];
                if (array.count == 0) {
                    [self.selectedContactArray addObject:contact];
                }else{
                    [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"youHaveSelectThisUser", nil)];
                }
            }
        }else{
            //单选
            if (![self.selectedContactArray containsObject:contact]) {
                [self.selectedContactArray removeAllObjects];
                [self.selectedContactArray addObject:contact];
                if (_searchController.active) {
                    [_searchController setActive:NO];
                }
            }
            if (lastIndexPath) {
                [tableView deselectRowAtIndexPath:lastIndexPath animated:NO];
            }
            lastIndexPath = indexPath;
        }
    }
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    YWHandler *contact = nil;
    if (_searchController.active) {
        contact = self.searchList[indexPath.row];
    }else{
        YWDepartment *department = self.groupArray[indexPath.section];
        contact = department.memberArray[indexPath.row];
    }
    if ([self.selectedContactArray containsObject:contact]) {
        [self.selectedContactArray removeObject:contact];
    }
    lastIndexPath = nil;
}
#pragma mark - private method
- (void)clickHeaderView:(YWContactHeadFooterView *)headerView{
    NSInteger tag = headerView.tag - KHeadViewBaseTag;
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:tag] withRowAnimation:UITableViewRowAnimationNone];
}

- (void)rightBarButtonItemEvent:(id)sender{
    if (self.isMultiSelect) {
        //多选
        if ([self.delegate respondsToSelector:@selector(selectMultipleContact:)]) {
            [self.delegate selectMultipleContact:_selectedContactArray];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }else{
        //单选
        if (_allJoinUser && _selectedContactArray.count==1) {
            //选择任务的参与者
            YWHandler *handler = _selectedContactArray[0];
            if ([self.delegate respondsToSelector:@selector(selectSingleContact:)]) {
                [self.navigationController dismissViewControllerAnimated:YES completion:nil];
                [self.delegate selectSingleContact:handler];
            }
//            NSString *tip = [NSString stringWithFormat:@"您正在将%@加入任务参与者，加入成功后%@将可以跟踪任务进度，并与任务内的其他参与者沟通",handler.userName?:@"",handler.userName?:@""];
//            UIAlertController* alertController= [UIAlertController alertControllerWithTitle:tip message:nil preferredStyle:UIAlertControllerStyleAlert];
//            [self presentViewController:alertController animated:YES completion:nil];
//            [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
//            [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                if ([self.delegate respondsToSelector:@selector(selectSingleContact:)]) {
//                    [self.delegate selectSingleContact:handler];
//                    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
//                }
//            }]];
        }else{
            if ([self.delegate respondsToSelector:@selector(selectSingleContact:)]) {
                [self.delegate selectSingleContact:_selectedContactArray.count ? _selectedContactArray[0] : nil];
            }
            //返回
            if (self.navigationController.childViewControllers.count < 2) {
                [self.navigationController dismissViewControllerAnimated:YES completion:nil];
            }else{
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
    }
}

- (void)leftBarButtonItemEvent:(id)sernder{
    //返回
    if (self.navigationController.childViewControllers.count < 2) {
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}
//搜索时过滤数据
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    NSString *searchString = searchController.searchBar.text;
    if (searchString.length==0) {
        self.searchList = nil;
        [self.tableView reloadData];
        return;
    }
    // 谓词的包含语法
    NSMutableArray *searchResults = [_allContacts mutableCopy];
    
    NSMutableArray *andMatchPredicates = [NSMutableArray array];
    
    NSMutableArray *searchItemsPredicate = [NSMutableArray array];
    
    // use NSExpression represent expressions in predicates.
    // NSPredicate is made up of smaller, atomic parts: two NSExpressions (a left-hand value and a right-hand value)
    
    // friendName field matching
    NSExpression *lhs = [NSExpression expressionForKeyPath:@"userName"];
    NSExpression *rhs = [NSExpression expressionForConstantValue:searchString];
    NSPredicate *finalPredicate = [NSComparisonPredicate
                                   predicateWithLeftExpression:lhs
                                   rightExpression:rhs
                                   modifier:NSDirectPredicateModifier
                                   type:NSContainsPredicateOperatorType
                                   options:NSCaseInsensitivePredicateOption];
    [searchItemsPredicate addObject:finalPredicate];
    
    // friendId field matching
    lhs = [NSExpression expressionForKeyPath:@"pinYin"];
    rhs = [NSExpression expressionForConstantValue:searchString];
    finalPredicate = [NSComparisonPredicate
                      predicateWithLeftExpression:lhs
                      rightExpression:rhs
                      modifier:NSDirectPredicateModifier
                      type:NSContainsPredicateOperatorType
                      options:NSCaseInsensitivePredicateOption];
    [searchItemsPredicate addObject:finalPredicate];
    // friendId field matching
    lhs = [NSExpression expressionForKeyPath:@"firstLetter"];
    rhs = [NSExpression expressionForConstantValue:searchString];
    finalPredicate = [NSComparisonPredicate
                      predicateWithLeftExpression:lhs
                      rightExpression:rhs
                      modifier:NSDirectPredicateModifier
                      type:NSContainsPredicateOperatorType
                      options:NSCaseInsensitivePredicateOption];
    [searchItemsPredicate addObject:finalPredicate];
    
    // at this OR predicate to our master AND predicate
    NSCompoundPredicate *orMatchPredicates = [NSCompoundPredicate orPredicateWithSubpredicates:searchItemsPredicate];
    [andMatchPredicates addObject:orMatchPredicates];
    //   }
    
    // match up the fields of the Product object
    NSCompoundPredicate *finalCompoundPredicate =
    [NSCompoundPredicate andPredicateWithSubpredicates:andMatchPredicates];
    if (self.searchList!= nil) {
        [self.searchList removeAllObjects];
    }
//    self.searchList = [[searchResults filteredArrayUsingPredicate:finalCompoundPredicate] mutableCopy];
    NSMutableArray * searchTemp = [[searchResults filteredArrayUsingPredicate:finalCompoundPredicate] mutableCopy];
    __block NSMutableArray * uniqueIdArray = [NSMutableArray array];
    [searchTemp enumerateObjectsUsingBlock:^(YWHandler *  _Nonnull handler, NSUInteger idx, BOOL * _Nonnull stop) {
        [uniqueIdArray addObject:@(handler.uniqueId)];
    }];
    NSSet *uniqueIdSet = [NSSet setWithArray:uniqueIdArray];
    NSArray * finishSearchArr = [uniqueIdSet allObjects];
    [finishSearchArr enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        YWHandler * handler = [[YWContactManager shareManager] getHandlerWithUniqueId:[obj integerValue]];
        [self.searchList addObject:handler];
    }];
    [self.tableView reloadData];
}

- (void)willPresentSearchController:(UISearchController *)searchController{
    self.navigationController.navigationBar.translucent = YES;
}

- (void)willDismissSearchController:(UISearchController *)searchController{
    self.navigationController.navigationBar.translucent = NO;
}

-(NSString *)nameToPinYinWith:(NSString *)name
{
    HanyuPinyinOutputFormat *outputFormat=[[HanyuPinyinOutputFormat alloc] init];
    [outputFormat setToneType:ToneTypeWithoutTone];
    [outputFormat setVCharType:VCharTypeWithV];
    [outputFormat setCaseType:CaseTypeLowercase];
    NSString *outputPinyin=[PinyinHelper toHanyuPinyinStringWithNSString:name withHanyuPinyinOutputFormat:outputFormat withNSString:@""];
    return outputPinyin;
}

-(NSString *)namToPinYinFisrtNameWith:(NSString *)name
{
    NSString * outputString = @"";
    for (int i =0; i<[name length]; i++) {
        outputString = [NSString stringWithFormat:@"%@%c",outputString,pinyinFirstLetter([name characterAtIndex:i])];
        
    }
    return outputString;
}

- (NSMutableArray*)searchList{
    if (!_searchList) {
        _searchList = [NSMutableArray array];
    }
    return _searchList;
}

- (void)dealloc{
    [_searchController.view removeFromSuperview];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
